<script lang="ts" setup name="LoginForm">
import Message from "@/components/message";
import { ref, watch } from "vue";
import useStore from "@/stores";
import { useRouter } from "vue-router";
import { useField, useForm } from "vee-validate";

const { user, cart } = useStore();
const router = useRouter();

const type = ref<"account" | "mobile">("account");
watch(type, () => {
  resetForm();
});

// 数据校验
const { validate, resetForm } = useForm({
  validationSchema: {
    account(value: string) {
      // 1.判断是否是空值
      if (!value) return "请输入用户名";
      // 2.正则 3-20个字符，需要以字母开头
      if (!/^\w{3,20}$/.test(value)) return "字母开头且3-20个字符";

      return true;
    },
    password(value: string) {
      // 1.判断是否是空值
      if (!value) return "请输入密码";
      // 2.正则 6-24位字符
      if (!/^\w{6,24}$/.test(value)) return "密码必须是6-24位字符";

      return true;
    },
    isAgree(value: boolean) {
      if (!value) return "请同意隐私条款";

      return true;
    },
    mobile(value: string) {
      // 1.判断是否是空值
      if (!value) return "请输入手机号";
      // 2.正则
      if (!/^1[35789]\d{9}$/.test(value)) return "手机号格式错误";

      return true;
    },
    code(value: string) {
      // 1.判断是否是空值
      if (!value) return "请输入验证码";
      // 2.正则
      if (!/^\d{6}$/.test(value)) return "验证码格式错误";

      return true;
    },
  },
});

const { value: account, errorMessage: accountError } =
  useField<string>("account");
const { value: password, errorMessage: passwordError } =
  useField<string>("password");
const { value: isAgree, errorMessage: isAgreeError } =
  useField<boolean>("isAgree");
const {
  value: mobile,
  errorMessage: mobileError,
  validate: validateMobile,
} = useField<string>("mobile");
const { value: code, errorMessage: codeError } = useField<string>("code");

// -------账号登录-----------
const login = async () => {
  // 1.收集数据验证数据的合法性
  const res = await validate();
  // console.log(res);

  if (type.value === "account") {
    if (!res.results.account || !res.results.password || !res.results.isAgree)
      return;
    // 2.axios发送ajax请求实现登录
    await user.login({ account: account.value, password: password.value });
  } else {
    if (!res.results.mobile || !res.results.code || !res.results.isAgree)
      return;
    // 2.axios发送ajax请求实现登录
    await user.mobileLogin({ mobile: mobile.value, code: code.value });
  }

  // 登录成功合并本地购物车数据到服务器
  cart.mergeLocalCart();
  // 3.成功或失败的提示
  Message.success("登录成功");
  // 4.如果成功实现跳转
  router.push("/");
};

// -------短信登录-----------

const mobileRef = ref<HTMLInputElement | null>(null);

const time = ref(60);
let timer = -1;
const content = ref("发送验证码");

// 1.获取短信
const send = async () => {
  if (time.value < 60) return;
  // 获取手机号并且数据要合法
  const { valid } = await validateMobile();
  if (!valid) {
    mobileRef.value!.focus();
    return;
  }

  await user.sendMobileMsg(mobile.value);
  Message.success("获取验证码成功");

  timer = setInterval(() => {
    if (time.value <= 1) {
      time.value = 60;
      content.value = "发送验证码";
      clearInterval(timer);
      return;
    }

    time.value--;
    content.value = `还剩${time.value}秒`;
  }, 1000);
};
</script>
<template>
  <div class="account-box">
    <div class="toggle">
      <a
        href="javascript:;"
        v-if="type !== 'account'"
        @click="type = 'account'"
      >
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a href="javascript:;" v-else @click="type = 'mobile'">
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <div class="form">
      <template v-if="type === 'account'">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input
              v-model="account"
              type="text"
              placeholder="请输入用户名或手机号"
            />
          </div>
          <div class="error" v-if="accountError">
            <i class="iconfont icon-warning" />{{ accountError }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <input
              v-model="password"
              type="password"
              placeholder="请输入密码"
            />
          </div>
          <div class="error" v-if="passwordError">
            <i class="iconfont icon-warning" />{{ passwordError }}
          </div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input
              ref="mobileRef"
              v-model="mobile"
              type="text"
              placeholder="请输入手机号"
            />
          </div>
          <div class="error" v-if="mobileError">
            <i class="iconfont icon-warning" />{{ mobileError }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <input v-model="code" placeholder="请输入验证码" />
            <span class="code" @click="send">{{ content }}</span>
          </div>
          <div class="error" v-if="codeError">
            <i class="iconfont icon-warning" />{{ codeError }}
          </div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <SealCheckbox v-model="isAgree"></SealCheckbox>
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <div class="error" v-if="isAgreeError">
          <i class="iconfont icon-warning" />{{ isAgreeError }}
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="login">登录</a>
    </div>
    <div class="action">
      <img
        src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
        alt=""
      />
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @sealColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @sealColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @sealColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    img {
      cursor: pointer;
    }
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
